package com.eatme.leetcode.problems;

import com.eatme.leetcode.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution203V3 {

    // 递归的"宏观"语意
    // 在以head为头节点的链表中删除值为val的节点，并返回结果链表的头结点
    public ListNode removeElements(ListNode head, int val, int depth) {
        String depthString = generateDepthString(depth);
        System.out.print(depthString);
        System.out.println("Call: remove "+val + " in "+head);
        if (head==null) {
            System.out.print(depthString);
            System.out.println("Return: "+head);
            return head;
        }
//        head.next = removeElements(head.next,val,depth+1);
//        return head.val == val ? head.next: head;
        ListNode res = removeElements(head.next,val,depth+1);
        System.out.print(depthString);
        System.out.println("After remove "+val+": " +res);
        ListNode ret;
        if (head.val == val) {
            head.next =null;
            ret = res;
        }else {
            head.next = res;
            ret = head;
        }
        System.out.print(depthString);
        System.out.println("Return: "+ret);
        return ret;
    }

    private String generateDepthString(int depth) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++)
            sb.append("--");
        return sb.toString();
    }

    public static void main(String[] args) {
        int[] nums = {1,2,6,3,4,5,6};
        ListNode head = new ListNode(nums);
        System.out.println(head);
        new Solution203V3().removeElements(head,6,0);
        System.out.println(head);
    }

}
